package com.zpark.service.impl;

import com.zpark.entity.User;
import com.zpark.mapper.UserMapper;
import com.zpark.service.IUserService;
import com.zpark.service.ex.InsertException;
import com.zpark.service.ex.PasswordNotMatchException;
import com.zpark.service.ex.UserNotFoundException;
import com.zpark.service.ex.UsernameDuplicateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public void reg(User user) {
        String username = user.getUsername();
        User result = userMapper.findByUsername(username);
        if (result != null){
            throw new UsernameDuplicateException("尝试注册用户名[" + username + "]以及被占用");
        }
        //判断用户名没有被占用，则注册


        //当前时间对象
        Date now = new Date();
        //进行加密
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = getMd5Password(user.getPassword(), salt);
        user.setPassword(md5Password);
        //保存盐值
        user.setSalt(salt);
        //保存isDelete
        user.setIsDelete(0);
        //保存日志
        user.setCreatedUser(username);
        user.setCreatedTime(now);
        user.setModifiedUser(username);
        user.setModifiedTime(now);
        Integer rows = userMapper.insertUser(user);
        //判断受影响的行数
        if(rows != 1){
            throw new InsertException("添加用户出现错误！");
        }
    }

    @Override
    public User login(String username, String password) {
        User result = userMapper.findByUsername(username);
        //判断查询结果是否为null
        if (result == null){
            throw new UserNotFoundException("用户不存在的错误");
        }

        //判断结果查询结果中的isDelete是否为1
        if(result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在的错误");
        }

        String salt = result.getSalt();
        String md5Password = getMd5Password(password, salt);
        //判断密码是否正确
        if (!result.getPassword().equals(md5Password)){
            throw new PasswordNotMatchException("密码错误");
        }

        //创建新的user对象封装需要用到的信息
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setPassword(result.getPassword());
        return user;
    }


    /**
     * 执行密码加密
     */
    private String getMd5Password(String password, String salt){
        /**
         * 加密规则：
         * 1.无视原始密码的强度
         * 2.使用UUID作为盐值，在原始密码的左右侧拼接
         * 3.循环加密三次然后转为Byte[]
         */
        for (int i = 0; i < 3; i++){
            //DigestUtils.md5DigestAsHex(btye[]) -- md5专属的加密算法 传入byte[]类型
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
